<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>合同管理</span>
      </div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="合同编号" prop="contractNo">
          <el-input v-model="searchForm.contractNo" placeholder="请输入合同编号" clearable/>
        </el-form-item>
        <el-form-item label="客户姓名" prop="name">
          <el-input v-model="searchForm.name" placeholder="请输入客户姓名" clearable/>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable/>
        </el-form-item>
        <el-form-item label="购买学科" prop="subject">
          <el-select v-model="searchForm.subject" placeholder="请选择购买学科" @change="getCourseList" clearable>
            <el-option
              v-for="dict in subjectOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="购买课程" prop="courseId">
          <el-select v-model="searchForm.courseId" placeholder="请选择购买课程" clearable>
            <el-option
              v-for="dict in courseOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            clearable
            type="daterange"
            align="right"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card">
      <el-button type="primary" style="margin-bottom: 10px" @click="handleAdd">添加</el-button>
      <el-table :data="pageData.data" style="width: 100%" border>
        <el-table-column label="合同编号" prop="contractNo"/>
        <el-table-column label="客户姓名" prop="name" />
        <el-table-column label="手机号" prop="phone" />
        <el-table-column label="购买学科" prop="subject" :formatter="subjectFormat" />
        <el-table-column label="购买课程" prop="courseId" :formatter="courseFormat"/>
        <el-table-column label="创建时间" prop="createTime" sortable/>`
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handlePreview(scope.row)">
              预览
            </el-button>
            <el-button size="mini" type="danger" @click="handleDetail(scope.row)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageData.pageNo"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageData.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.totalCount">
      </el-pagination>

      <el-dialog title='新增合同' :visible.sync="dialogFormVisible">
        <el-form :model="saveForm" :rules="rules" ref="saveForm" label-width="100px" inline>
          <el-form-item label="客户姓名" prop="name">
            <el-input v-model="saveForm.name" placeholder="请输入客户姓名" />
          </el-form-item>
          <el-form-item label="客户手机号" prop="phone">
            <el-input v-model="saveForm.phone" placeholder="请输入客户手机号" />
          </el-form-item>
          <el-form-item label="合同编号" prop="contractNo">
            <el-input v-model="saveForm.contractNo" placeholder="请输入合同编号" maxlength="20" />
          </el-form-item>
          <el-form-item label="购买学科" prop="subject">
            <el-select v-model="saveForm.subject" placeholder="请选择购买学科" @change="getCourseList">
              <el-option
                v-for="dict in subjectOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
          <el-form-item label="购买课程" prop="courseId">
            <el-select v-model="saveForm.courseId" placeholder="请选择购买课程">
              <el-option
                v-for="dict in courseOptions"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="渠道来源" prop="channel">
            <el-select v-model="saveForm.channel" placeholder="请输入渠道来源" @change="getActivityList">
              <el-option
                v-for="dict in channelOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"/>
            </el-select>
          </el-form-item>
          <el-form-item label="活动信息" prop="activityId">
            <el-select v-model="saveForm.activityId" placeholder="请选择活动信息">
              <el-option
                v-for="item in activityOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="上传合同" prop="fileName">
            <el-upload
              ref="upload"
              action="/api/file/upload"
              :limit="1"
              :before-upload="beforeFileUpload"
              :on-success="handleFileSuccess"
              :headers="{'Authorization': 'Bearer '+ $store.state.token}"
              :show-file-list="true">
              <!-- 上传按钮 -->
              <el-button type="primary">上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="doSave">确 定</el-button>
        </div>
      </el-dialog>

       <el-dialog title='预览合同' :visible.sync="dialogPreviewVisible" width="80%" top="5vh">
          <div style="height: 500px;">
            <iframe 
              :src="pdfSrc" 
              width="100%" 
              height="100%" 
              frameborder="0"
              v-if="pdfSrc">
            </iframe>
            <div v-else style="text-align: center; padding: 50px; color: #999;">
              暂无PDF文件
            </div>
          </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      pdfSrc: '',       // PDF文件路径或URL
      // 购买课程字典
      subjectOptions: [],
      // 购买学科字典
      courseOptions: [],
      // 渠道字典
      channelOptions:[],
      dateRange:[],
      activityOptions:[],
      //查询的数据模型
      searchForm: {
        //过滤条件
        contractNo: null,
        name: null,
        phone: null,
        subject: null,
        courseId: null,
        status: null,
        beginTime: null,
        endTime: null,
        
        //分页条件
        pageNo: 1,
        pageSize: 5,
      },
      //分页数据模型
      pageData: {
        data: [], // 分页数据
        pageNo: 1, // 当前页
        pageSize: 5, // 一页的大小
        totalCount: 0, // 总数据量
        totalPageCount: 0, // 总页数
      },
      //控制对话框显示还是隐藏
      dialogFormVisible: false,
      dialogPreviewVisible:false,
      //新增的数据模型
      saveForm: {
        id: null,
        name: null,
        phone: null,
        contractNo: null,
        subject: null,
        courseId: null,
        channel: null,
        activityId: null,
        fileName: null
      },
      //验证数据模型
      rules:{
        name: [
          { required: true, message: '客户姓名不能为空', trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '客户手机号不能为空', trigger: 'blur' },
        ],
        subject: [
          { required: true, message: '购买学科不能为空', trigger: 'change' }
        ],
        courseId: [
          { required: true, message: '购买课程不能为空', trigger: 'change' }
        ],
        contractNo: [
          { required: true, message: '合同编号不能为空', trigger: 'blur' }
        ],
      },
    }
  },
  created() {
    this.doSearch();
    this.getDicList();
  },
  methods: {
   setPdfSource(src) {
      // 直接设置 PDF 文件路径，使用 iframe 显示
      this.pdfSrc = "http://localhost:9000/"+src;
    },
    getDicts(dictType){
      return new Promise((resolve, reject) => {
        this.$axios.get("/api/sys/dictData/optionselect/"+dictType)
          .then((res) => {
            if (res.data.code == 200) {
              resolve(res.data);
            } else {
              this.$message.error(res.data.msg);
            }
          })
      })
    },
    //查询数据字典
    getDicList () {
      this.getDicts('course_subject').then(response => {
        this.subjectOptions = response.data
      })
      this.getDicts('clues_item').then(response => {
        this.channelOptions = response.data
      })
    },
    getCourseList (subject) {
      this.$axios.get("/api/tb/course/optionselect?subject="+subject)
        .then((res) => {
          if (res.data.code == 200) {
            this.courseOptions = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        })
    },
    //查询活动下拉列表
    getActivityList(channel) {
      this.$axios.get("/api/tb/activity/optionselect/"+channel)
        .then((res) => {
          if (res.data.code == 200) {
            this.activityOptions = res.data.data;
          } else {
            this.$message.error(res.data.msg);
          }
        })
    },
    // 回显数据字典
    selectDictLabel(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].dictValue == ('' + value)) {
          actions.push(datas[key].dictLabel);
          return true;
        }
      })
      return actions.join('');
    },
    // 意向学科字典翻译
    subjectFormat (row) {
      return this.selectDictLabel(this.subjectOptions, row.subject)
    },
    // 课程翻译
    courseFormat (row) {
      const course = this.courseOptions.find(item => item.id === row.courseId)
      if (course) {
        return course.name
      }
      return ''
    },
    //查询用户信息
    doSearch() {
      //获取开始时间和结束时间
      if (this.dateRange) {
        this.searchForm.beginTime = this.dateRange[0]
        this.searchForm.endTime = this.dateRange[1]
      }else{
        this.searchForm.beginTime =null;
        this.searchForm.endTime =null;
      }
      this.$axios.get("/api/tb/contract/list", {params:this.searchForm})
        .then((res) => {
          if (res.data.code == 200) {
            this.pageData.pageNo = res.data.data.current;
            this.pageData.pageSize = res.data.data.size;
            this.pageData.totalCount = res.data.data.total;
            this.pageData.totalPageCount = res.data.data.pages;
            this.pageData.data = res.data.data.records;
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //改变每页显示的条数
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.doSearch();
    },
    //改变当前的页码数
    handleCurrentChange(val) {
      this.searchForm.pageNo = val;
      this.doSearch();
    },
    //清空新增表单数据
    reset () {
      this.saveForm = {
        id:null,
        name:null,
        channel:null,
        info:null,
        type:null,
        discount:null,
        vouchers:null,
        beginTime:null,
        endTime:null,
      };
    },
    //添加
    handleAdd() {
      //1.清空模型数据
      this.reset();
      //2.显示对话框
      this.dialogFormVisible = true;
    },
    //保存
    doSave() {
      this.$refs["saveForm"].validate((vali) => {
        if (vali) {
          //发送ajax请求
          this.$axios.post("/api/tb/contract/save", this.saveForm)
            .then((res) => {
              if (res.data.code == 200) {
                //1.关闭对话框
                this.dialogFormVisible = false;
                //2.友好提示
                this.$message.success(res.data.msg);
                //3.刷新表格
                this.doSearch();
              } else {
                //1.友好提示
                this.$message.error(res.data.msg);
              }
            })
            .catch((err) => {
              console.log(err);
            });
        }
      });
    },
    // 查看
    handleDetail (row) {
      this.$router.push('/contract/details?id='+row.id)
    },
    // 预览
    handlePreview(row) {
       this.setPdfSource(row.fileName);
       this.dialogPreviewVisible=true;
    },
    handleFileSuccess(res, file) {
      this.saveForm.fileName = res.data;
    },
    beforeFileUpload(file) {
      const isPDF = file.type === 'application/pdf';
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isPDF) {
        this.$message.error('上传文件只能是 pdf 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!');
      }
      return isPDF && isLt2M;
    }
  },
}
</script>

<style scoped>
</style>

